'use strict';

var fs = require('fs'),
classBuilder = require('./util/classBuilder'),
Task = require('./task/Task').Task; // It registers the generic task type

exports.Runner = classBuilder.define({

    construct: function (conf) {

        // The tasks that are going to be executed by this runner
        this.tasks = {};

        // The id of the starting task
        this.main = null;

        this.results = {}; // The results of executing task

        if (conf) {
            this.configure(conf);
        }
    },

    // Loads a configuration from a file and starts running the tasks
    loadAndRun: function (path, params) {
        var me = this;

        fs.readFile(path, function (error, data) {
            if (error) {
                throw error;
            }

            var conf = eval('(' + data +')');
            me.configure(conf);
            me.run(params);
        });
    },

    // Configures this runner from the configuration object
    configure: function (conf) {

        conf.tasks.forEach(function (taskConf) {

            var task = Task.create(taskConf);
            this.registerTask(task);

        }, this);

        this.main = conf.main;
    },

    registerTask: function (task) {
        this.tasks[task.id] = task;
        task.runner = this;
    },

    getTask: function (id) {
        return this.tasks[id];
    },

    run: function (params) {
        console.log('Runner started');

        var task = this.getTask(this.main);
        task.run(params);

        console.log('Runner finished');
    }
});
